import React, { useEffect, useMemo, useState } from "react";
import { Table, Space, ImgDefault, Icon, message, Spin, Progress, Tag, Button, Modal } from '@bytedance/mona-ui';
import { format } from './postDataInfo'
function EditProgress(props: any) {
    const { editProdectId } = props;
    if (!editProdectId || !editProdectId.length) return null

    const editProdectColums = [
        {
            title: '商品信息',
            key: 'info',
            width: 300,
            render: (text: any, record: any) => {
                return <Spin spinning={record.lodinStatus}>
                    <Space>
                        <ImgDefault
                            imgSrc={(() => {
                                const imgae = record.detail?.img.replace("obj/", "")
                                return imgae + "~110x110_q75.image"
                            })()}
                            mask={false}
                            width={60}
                            height={60}></ImgDefault>
                        <Space direction="vertical" size={4}>
                            <div
                                className="title"
                                style={{
                                    fontSize: 12,
                                    color: "#252931",
                                    // 省略号
                                    width: 200,
                                    overflow: "hidden",
                                    textOverflow: "ellipsis",
                                    whiteSpace: "nowrap"
                                }}>
                                {record.detail?.name}
                            </div>
                            <div
                                className="isduer"
                                style={{
                                    color: "#898b8f",
                                    fontSize: 12
                                }}>
                                ID:{record.detail?.product_id}
                                <Icon
                                    type="CopyIcon"
                                    className="copyiconitem"
                                    style={{
                                        marginLeft: 5,
                                        cursor: "pointer"
                                        // opacity: 0,
                                        // ':hover': {
                                        //     color: '#1966FF'
                                        // }
                                    }}
                                    onClick={() => copyToClipboard(record.detail?.product_id)}
                                />
                            </div>
                        </Space>
                    </Space>
                </Spin>

            }
        },
        {
            title: '获取商品详情',
            key: 'getDeteAils',
            align: 'center',
            width: 100,
            render: (text: any, record: any) => {
                return <Spin spinning={record.lodinStatus}>
                    {!record.lodinStatus && <Progress type="circle" percent={100} width={20} />}
                </Spin>
            }
        },
        {
            title: '创建AI主图进度',
            key: 'getDeteAils',
            align: 'center',
            width: 100,
            render: (text: any, record: any) => {
                return <Spin spinning={record.isAiEdit ? !!(!record.aiOuterStatus || record.aiOuterStatus?.run_status == 0 || record.aiOuterStatus?.run_status == 4 || record.aiOuterStatus?.run_status == 1) : false}>
                    {(record.isAiEdit ? !!(record.aiOuterStatus && record.aiOuterStatus?.run_status == 2 || record.aiOuterStatus?.run_status == 3) : true) && <Progress type="circle" percent={100} width={20} />}
                </Spin>
            }
        },
        {
            title: '发布商品',
            key: 'getDeteAils',
            align: 'center',
            width: 100,
            render: (text: any, record: any) => {
                return <Spin spinning={record.lodinStatus}>
                    <Tag.Status type={record.upTypeText}>{record.upStatusText}</Tag.Status>
                    {record.upLodinStuas == 5 && <>
                        <div className="err">{record.errText}</div>
                        <Button type="link" onClick={() => {
                            open(`https://fxg.jinritemai.com/ffa/g/create?product_id=${record.detail?.product_id}&cid=23961`)
                        }}>前往官方编辑</Button>
                    </>}
                    {/* {record.upLodinStuas == 5 && <div className="copyiconitem" style={{ marginLeft: 5, cursor: "pointer" }} onClick={() => upEditDataFun(record)}>重新上传</div>} */}
                </Spin>
            }
        }
    ]
    function copyToClipboard(text) {
        navigator.clipboard
            .writeText(text)
            .then(function () {
                message.success("复制成功")
            })
            .catch(function (err) {
                message.error("复制失败")
            })
    }
    const [setUpItemData, setUpItemDataFun] = useState<any>([])
    const [percentRouters, setPercentRouters] = useState(0)

    useEffect(() => {
        // console.log('setUpItemData', setUpItemData)
        if (setUpItemData.length > 0) {
            upEditDataFun()
        }
        // console.log('setUpItemData', setUpItemData)
        const lenter = setUpItemData.filter(item => {
            // console.log('item', item)
            // return item.upLodinStuas == 4 || item.upLodinStuas == 5
            return item.upLodinStuas == 4 || item.upLodinStuas == 5
        }).length
        // console.log('lenter', lenter)
        setPercentRouters(Number((lenter / editProdectId.length * 100).toFixed(2)))

        if (lenter == editProdectId.length) {
            Modal.success({
                title: '提示',
                content: '全部上传完成, 数据更新可能延迟，请次日查看',
                // onOk() {
                //     setUpItemDataFun([])
                // },
            });
        }
    }, [setUpItemData])

    function upEditData() {
        const lenter = editProdectId.filter(item => {
            // console.log('item', item)
            // return item.upLodinStuas == 4 || item.upLodinStuas == 5
            return item.upLodinStuas == 4 || item.upLodinStuas == 5
        }).length
        // console.log('lenter', lenter)
        setPercentRouters(Number((lenter / editProdectId.length * 100).toFixed(2)))
        editProdectId.forEach(item => {
            if (!item.upLodinStuas) {
                item.upLodinStuas = 1 // 1 等待进行 2可以上传 3上传中 4上传完成 5上传失败
                item.upStatusText = '数据处理中...'
                item.upTypeText = 'cancel'
                setUpItemData.push(item)
                setUpItemDataFun(myseta(setUpItemData))
            }

            if (item.lodinStatus) return

            if (item.isAiEdit ? !item.aiOuterStatus || item.aiOuterStatus?.run_status == 0 || item.aiOuterStatus?.run_status == 4 || item.aiOuterStatus?.run_status == 1 : false) return
            if (item.upLodinStuas == 1) {
                item.upLodinStuas = 2
                item.upStatusText = '等待发布'
                item.upTypeText = 'warn'
                setUpItemDataFun(myseta(setUpItemData))
            }

        })



    }
    function myseta(ary) {
        // 过滤id相同的项
        return ary.filter((item, index, self) =>
            index === self.findIndex((t) => (
                t.id === item.id
            ))
        )

    }

    function upEditDataFun() {
        // console.log('进行单个上传', setUpItemData)

        setUpItemData.forEach(item => {
            if (item.upLodinStuas == 2) {
                item.upLodinStuas = 3
                item.upStatusText = '正在上传'
                item.upTypeText = 'default'
                setUpItemDataFun(myseta(setUpItemData))
                // console.log('进行单个上传', item)
                refoGetImageInfod(item)
            }
        })
    }

    function refoGetImageInfod(item) {
        // console.log('item', item)
        if (item.isAiEdit) {
            const getAiLlist = item.aiOuterStatus.run_end_image_obj.filter(conter => !conter.extra_properties?.pic_scale)

            item.setReForData.picimageList[0].url = getAiLlist[0]?.img_url || item.setReForData.picimageList[0].url
        }

        console.log('上传的处理数据', item)
        format(item).then(res => {
            console.log('上传的数据', res)
            if (res.data && res.data.code == 10000) {
                item.upLodinStuas = 4
                item.upStatusText = '发布成功'
                item.upTypeText = 'success'
            } else {
                item.upLodinStuas = 5
                item.upStatusText = '发布失败'
                item.upTypeText = 'error'
                item.errText = res.data.sub_msg
            }
            setUpItemDataFun(setUpItemData => [...setUpItemData])
        }).catch(err => {
            console.log('上传失败', err)
            item.upLodinStuas = 5
            item.upStatusText = '发布失败'
            item.upTypeText = 'error'
            item.errText = '发布失败'
            setUpItemDataFun(setUpItemData => [...setUpItemData])
        })
    }

    useMemo(() => {
        upEditData()
    }, [editProdectId])


    return (
        <div className="edit-progress">
            <Space direction="vertical">
                <Space align="center">
                    <span>处理进度：</span>
                    <Progress percent={percentRouters} style={{
                        width: "500px"
                    }} />
                </Space>
                <Table pagination={false} rowKey='id' scroll={{ y: 800 }} dataSource={editProdectId} columns={editProdectColums}></Table>
            </Space>

        </div>
    )
}
export default EditProgress